package cn.lblbc.todo.repository

import cn.lblbc.todo.Task
import cn.lblbc.todo.db.TaskDao
import cn.lblbc.todo.db.TaskEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map

class TaskRepository(private val taskDao: TaskDao) {
    
    fun getAllTasks(): Flow<List<Task>> = taskDao.getAllTasks().map { entities ->
        entities.map { it.toTask() }
    }
    
    fun getActiveTasks(): Flow<List<Task>> = taskDao.getActiveTasks().map { entities ->
        entities.map { it.toTask() }
    }
    
    fun getCompletedTasks(): Flow<List<Task>> = taskDao.getCompletedTasks().map { entities ->
        entities.map { it.toTask() }
    }
    
    suspend fun insertTask(task: Task) {
        taskDao.insertTask(task.toEntity())
    }
    
    suspend fun updateTask(task: Task) {
        taskDao.updateTask(task.toEntity())
    }
    
    suspend fun deleteTask(task: Task) {
        taskDao.deleteTask(task.toEntity())
    }
    
    suspend fun deleteTaskById(taskId: Long) {
        taskDao.deleteTaskById(taskId)
    }
    
    private fun TaskEntity.toTask(): Task {
        return Task(
            id = id,
            title = title,
            description = description,
            dueDate = dueDate,
            isCompleted = isCompleted,
            createdAt = createdAt
        )
    }
    
    private fun Task.toEntity(): TaskEntity {
        return TaskEntity(
            id = id,
            title = title,
            description = description,
            dueDate = dueDate,
            isCompleted = isCompleted,
            createdAt = createdAt
        )
    }
}